var userJs = function(targetObj){
	this.targetObj = targetObj;
	this.sysUtils = new kendoUtils();
	this.init();
	return this;
};

userJs.prototype={
		init:function(){
			var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj.find(".search-panel"));
			var bindFunctionArray = [{fName:"queryInfo",fs:this.findGridData},{fName:"resetInfo",fs:this.resetInfo}];
			this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
			this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
			this.createGrid();
		},
		//创建Grid
		createGrid:function(){
			var columns = this.gridColumns();
			var that = this;
			this.sysUtils.createGird(this.targetObj.find("#userList"), {
				dataSource:[],
				selectable: "single",
				reorderable: true,
				columnMenu: true,
				resizable: true,
				pageable: {input: true,
					numeric: false},
					columns: columns,
					dataBound:function(){
						that.targetObj.find("#userList").find("tr:gt(0)").unbind("dblclick");
						that.targetObj.find("#userList").find("tr:gt(0)").dblclick(function(e){
							var grid = that.targetObj.find("#userList").data("kendoGrid");
							var dataItem = grid.dataItem(grid.select());
							//打开查看窗口
							that.openUserWindow(dataItem["userAccount"]);
						});	
					}
			});
		},
		/*
		 * 重置按钮
		 */
		resetInfo:function(e){
			var that = $(e.target).data("that");
			that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
		},
		findGridData:function(e){
			var that = this;
			if(isNotEmpt(e)){
				that = $(e.target).data("that");
			}
			if(validityForm(that.targetObj)){
				var jsonObj = that.sysUtils.getBindDocJson();
				//转换时间格式
				if(isNotEmpt(jsonObj["beginTime"])){
					jsonObj["beginTime"] = kendo.toString(jsonObj["beginTime"],'yyyy-MM-dd HH:mm:ss');
				}
				if(isNotEmpt(jsonObj["endTime"])){
					jsonObj["endTime"] = kendo.toString(jsonObj["endTime"],'yyyy-MM-dd HH:mm:ss');
				}
				var kendoGrid  = that.targetObj.find("#userList").data("kendoGrid");
				var urls = baseApiPath +"user/userList";
				var dataT = {curdatetime:new Date().getTime(),json:JSON.stringify(jsonObj)};
				var dataSource = that.sysUtils.getDataSource({url:urls,data:dataT,dataType:"odata"});
				kendoGrid.setDataSource(dataSource); 
			}
		},
		/*
		 * 加载list 列表
		 */
		gridColumns:function(){
			var userType=user.userType;
			var  items=[{
				width:30,
				headerTemplate: '<input type="checkbox" gridId="userList" onclick="gridCheckAll(this)" />',
				template: '<input name="userCheck" type="checkbox" value="${userAccount}"/>'
			},
			{
				title: "用户名",
				field:"userName"
			},

			{
				title: "账户名",
				field: "userAccount"
			},
			{
				title: "联系电话",
				field: "mobile",
			},
			{
				title: "邮箱地址",
				field: "email",
			},
			{
				title:"联系地址",
				field:"address"
			},
			{
				title: "创建人",
				field: "createBy"
			},   
			{
				title: "创建时间",
				field: "createTime"
			},
			{
				title: "类型",
				template:"#:Utils.getModelNameByParentKey(BASIS.USER_TYPE.ROOT,userType,Utils.systemType.SYS)#"
			},
			{
				title: "状态",
				template:"#:Utils.getModelNameByParentKey(BASIS.DATA_STATUS.ROOT,status,Utils.systemType.SYS)#"
			}];
			return items;
		},
		updateStatus:function(_self){
			var that=this;
			var userId=$(_self).attr("data-id");
			JsonpAjax(baseApiPath+"user/updateStatus?userId=" + userId,null,"json",function(result){
				if(result.success){
					that.findGridData();
				}else{
					notification({ title:"操作失败",message:result.msg},'info');
				}
			}); 
		},
		/**
		 * 弹出用户新增、修改或者查询界面
		 */
		openUserWindow:function(userAccount,isEdit){
			var that = this;
			var titles = "";
			that.editResult = null;
			that.isEdit = null;
			var openwidonw = function(){
				that.userDivId = that.sysUtils.openWindow(that.userDivId,{
					title:titles,
					height:"555px",
					width:"790px",
					resizable:false,
					content:"views/framework/user/edit.html"
				}, true);
			};
			var ajaxPost = function(){
				JsonpAjax(baseApiPath+"user/queryUserInfo?userAccount=" + userAccount,null,"json",function(result){
					that.editResult = result;
					openwidonw();
				}); 
			};
			if(undefined == userAccount && null == isEdit){  //表示新增界面
				titles = "新增用户信息";
				that.isEdit = false;
				openwidonw();
			}else if(true == isEdit){  //编辑界面
				//获取选中行的用户编号
				var grid = this.targetObj.find("#userList").data("kendoGrid");
				var dataItem = grid.dataItem(grid.select());
				if(null == dataItem){
					notification({ title:"操作失败",message:"请选择至少一条需要修改的记录!!"},'info');
					return;
				}
				userAccount = dataItem["userAccount"];
				titles = "编辑用户信息";
				that.isEdit = true;
				ajaxPost();
			}else{    //查询界面
				titles = "查询用户信息";
				that.isEdit = false;
				ajaxPost();
			}
		},
		/**
		 * 删除用户信息，只做逻辑删除
		 */
		deleteUser:function(){
			var that = this;
			//获取呗选中的选择框
			var userIdList = "";
			that.targetObj.find("input[name='userCheck']:checked").each(function(){
				userIdList += "'" + $(this).val() +"',";
			});
			if("" == userIdList){
				notification({ title:"操作失败",message:"请选择至少一条需要删除的记录!!"},'info');
				return;
			}
			notification({ title:"确认信息",message:"确定需要删除选中的用户信息？"},'confirm',{callback:function(){
				userIdList = userIdList.substring(0, userIdList.length - 1);
				JsonpAjax(baseApiPath+"user/deleteUserInfo",userIdList,"json",function(result){
					that.findGridData();
				});
			}});
		},
		/**
		 * 修改资源状态
		 */
		updateResourceStatus:function(statusCode){
			var that = this;
			var statusName = null;
			if("Start" == statusCode){
				statusName = "启用";
			}else if("Stop" == statusCode){
				statusName = "停用";
			}else{
				notification({ title:"操作失败",message:"状态码异常，请重试!!"},'info');
				return;
			}
			//获取呗选中的选择框
			var valStr = "";
			this.targetObj.find("input[name='userCheck']:checked").each(function(){
				valStr += "'" + $(this).val() +"',";
			});
			if("" == valStr){
				notification({ title:"操作失败",message:"请勾选至少一条需要"+statusName+"的记录!!"},'info');
				return;
			}
			notification({ title:"确认信息",message:"确定需要"+statusName+"选中的系统用户信息？"},'confirm',{callback:function(){
				valStr = valStr.substring(0, valStr.length - 1);
				JsonpAjax(baseApiPath+"user/updateStatus?ids="+valStr+"&statusCode="+statusCode,"","json",function(result){
					that.findGridData();
				});
			}});
		},
		/**
		 * 重置密码
		 */
		resetPassword:function(){
			//获取呗选中的选择框
			var valStr = "";
			this.targetObj.find("input[name='userCheck']:checked").each(function(){
				valStr +=  $(this).val() + SEPARATOR;
			});
			if("" == valStr){
				notification({ title:"操作失败",message:"请勾选至少一条需要"+statusName+"的记录!!"},'info');
				return;
			}
			notification({ title:"确认信息",message:"确定需要重置选中的系统用户密码？"},'confirm',{callback:function(){
				valStr = valStr.substring(0, valStr.length - 1);
				JsonpAjax(baseApiPath+"user/resetPassword?userAccounts="+valStr,"","json",function(result){
					
				});
			}});
		}
};



var userEditJs = function(targetObj){
	this.targetObj = targetObj;
	this.sysUtils = new kendoUtils();
	this.resourcesNodeInfo = null;
	this.init();
	return this;
};

userEditJs.prototype={
		init:function(){
			var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
			var bindFunctionArray = [{fName:"saveUserInfo",fs:this.saveUserInfo},{fName:"cancelSave",fs:closeWindow}];
			this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
			this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
			var statusStart = Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_START,Utils.systemType.SYS);
			var statusDiv = this.targetObj.find("input[data-bind='value:status']");
			Utils.createDataDictDropDownList({div:statusDiv,parentModelKey:BASIS.DATA_STATUS.ROOT,select:statusStart},this,this.loadData,Utils.systemType.SYS);
		},
		/**
		 * 组织架构树
		 */
		orgInfoTree:function(){
			var that = this;
			JsonpAjax(baseApiPath + "departMent/orgInfoTree",null,"json",function(result){
				if(result.constructor == Object){
					that.targetObj.find("#departmentTreeView").kendoTreeView({
						dataTextField:"fullName",
						dataSource:[result],
						checkboxes: {
							checkChildren: false,
							template: "<input type='radio' name='departGroup' id='#= item.id #' style='margin-top: 3px;' />"
						},
						schema: {
							model: {
								hasChildren: "hasChildren",
								id: "id",
								children: "items",
								expanded:"expanded"
							}
						},
						dataBound:function(e){
							if(undefined == e["node"]){   //判断是否节点是否加载完成
								this.expand(".k-item");
								if (null != userInfoJs.editResult && true == userInfoJs.isEdit){        //编辑
									that.targetObj.find("#" + userInfoJs.editResult["orgId"])[0].checked = true;
								}else if(null != userInfoJs.editResult && false == userInfoJs.isEdit){   //查看
									that.targetObj.find("input[type='radio']").attr("disabled","disabled");
									that.targetObj.find("#" + userInfoJs.editResult["orgId"])[0].checked = true;
								}
							}
						}
					});
				}
			});
		},
		//查询角色信息
		loadUserRole:function(){
			var that = this;
			JsonpAjax(baseApiPath + "userRole/findUserRoleList",null,"json",function(result){
				var userRoleView = that.targetObj.find("#userRoleView");
				for(var i = 0; i < result.length; i ++){
					var userRoleDiv = $('<div class="holder"> <div class="check"><input type="checkbox"/></div> '
							+ '<div class="name">'+result[i]["roleName"]+"("+result[i]["roleCode"]+")"+'</div></div>');
					userRoleDiv.find("input").data("userRole",result[i]);
					userRoleView.append(userRoleDiv);
					if(null != userInfoJs.editResult && null != userInfoJs.editResult["systemRoleUserList"]){
						//选中角色信息
						for(var j = 0 ; j < userInfoJs.editResult["systemRoleUserList"].length; j++){
							if( result[i]["id"] == userInfoJs.editResult["systemRoleUserList"][j]["roleId"]){
								userRoleDiv.find("input")[0].checked = true;
							}
						}
					}
				} 
				if(false == userInfoJs.isEdit && null != userInfoJs.editResult){  //查看
					userRoleView.find("input[type='checkbox']").attr("disabled","disabled");
				}
			}); 
		},
		//检查是否需要加载展示数据
		loadData:function(){
			this.orgInfoTree();  //加载组织架构树
			this.loadUserRole(); //加载用户角色信息
			if(null == userInfoJs.editResult) return; //新增啥都不需要做
			//加载数据
			this.sysUtils.setBindFieldValue(userInfoJs.editResult);
			if(userInfoJs.isEdit == false){  //表示查看
				//查看需要屏蔽一些字段
				var that = this;
				this.targetObj.find("input[type='password']").parents("div[class='hint-text']").remove();
				this.targetObj.find("input[ck='ckPS']").parents("div[class='hint-text']").remove();
				this.targetObj.find(".basicInfo-btn").find(".save").remove();
				this.targetObj.find("div.upload-case").find("a").remove();
				this.targetObj.find("input").attr("disabled","disabled");
				this.targetObj.find("textarea").attr("disabled","disabled");
				this.targetObj.find("input[data-bind='value:status']").data("kendoDropDownList").enable(false);
				//ajaxPost();
			}else{    //表示编辑
				//编辑不允许改密码、用户账户
				this.targetObj.find("input[type='password']").attr("disabled","disabled");
				this.targetObj.find("input[data-bind='value:userAccount']").attr("disabled","disabled");
				var password = this.targetObj.find("input[data-bind='value:userPassword']").val();
				this.targetObj.find("input[ck='ckPS']").val(password);
				//ajaxPost();
			}
		},
		saveUserInfo:function(e){
			var that =  $(e.target).data("that");
			if(validityForm(that.targetObj)){
				var userInfoJson = that.sysUtils.getBindDocJson();
				var ckPs = that.targetObj.find("input[ck='ckPS']").val();
				if(!userInfoJs.isEdit){
					if(isEmpty(ckPs)){
						notification({ title:"操作失败",message:"确认密码为必填项"},'info');
						return;
					}else if(ckPs != userInfoJson["pwd"]){
						notification({ title:"操作失败",message:"	两次输入的密码不一致"},'info');
						return;
					}
				}
				//所属组织机构	   
				var checkedRadio = that.targetObj.find("input[name='departGroup']:checked");
				if(checkedRadio.length <= 0){
					notification({ title:"操作失败",message:"请选择用户所属组织"},'info');
					return;
				}
				userInfoJson["orgId"] = checkedRadio.attr("id");
				//所拥有的角色
				var checkedCheckbox = that.targetObj.find("#userRoleView").find("input[type='checkbox']:checked");
				var userRoleIds = "";
				for(var i = 0; i < checkedCheckbox.length; i++){
					userRoleIds += $(checkedCheckbox[i]).data("userRole")["id"] + SEPARATOR; 
				}
				if(null == userRoleIds){
					notification({ title:"操作失败",message:"请选择用户拥有角色"},'info');
					return;
				}	
				userInfoJson["userRoleIds"] = userRoleIds.substring(0,userRoleIds.length - 1);
				JsonpAjax(baseApiPath+"user/saveUser?isEdit=" + userInfoJs.isEdit,JSON.stringify(userInfoJson),"json",function(result){
					if(result.constructor == Object){
						closeWindow();
						userInfoJs.findGridData();
					}
				}); 
			}
		}
};
